package com.qyhl.shop.shop.rush.detail;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.style.TextAppearanceSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.tools.ScreenUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.shop.shop.shop.ShopDetailActivity;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.Md5Builder;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopBaseBannerBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopRushDetailBean;
import com.qyhl.webtv.commonlib.entity.shop.ShopRushPurchaseTicketBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.ResizableImageView;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.androidx.XBanner;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_RUSH_PURCHASE_DETAIL)
public class ShopRushPurchaseDetailActivity extends BaseActivity implements ShopRushPurchaseDetailContract.ShopRushPurchaseDetailView {
    @BindView(R2.id.rush_purchase_txt)
    TextView rushPurchaseTxt;
    @BindView(R2.id.rest_num)
    TextView restNum;
    @BindView(R2.id.pic_one)
    RoundedImageView picOne;
    @BindView(R2.id.pic_two)
    RoundedImageView picTwo;
    @BindView(R2.id.pic_three)
    RoundedImageView picThree;
    @BindView(R2.id.xBanner)
    XBanner xBanner;
    @BindView(R2.id.message_head)
    RoundedImageView messageHead;
    @BindView(R2.id.message_txt)
    TextView messageTxt;
    @BindView(R2.id.message)
    RelativeLayout message;
    @BindView(R2.id.price)
    TextView price;
    @BindView(R2.id.time_day)
    TextView timeDay;
    @BindView(R2.id.time_hour)
    TextView timeHour;
    @BindView(R2.id.time_minute)
    TextView timeMinute;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.expiry_date)
    TextView expiryDate;
    @BindView(R2.id.address)
    TextView address;
    @BindView(R2.id.organization)
    TextView organization;
    @BindView(R2.id.introduction)
    TextView introduction;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.time_tips)
    TextView timeTips;
    @BindView(R2.id.org_tag)
    ImageView orgTag;
    @BindView(R2.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R2.id.head_layout)
    RelativeLayout headLayout;
    @BindView(R2.id.image_layout)
    RelativeLayout imageLayout;

    @Autowired(name = "id")
    int giftId;


    private ShopRushPurchaseDetailPresenter mPresenter;

    private ShopRushDetailBean mBean;

    private CountDownTimer countDownTimer;

    private CountDownTimer overTimer;

    private final static int REQUEST_CODE = 100;

    private ShopRushPurchaseTicketBean ticketBean;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_rush_purchase_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarDarkFont(true).fitsSystemWindows(true).statusBarColor(R.color.global_background).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new ShopRushPurchaseDetailPresenter(this);

        BusFactory.getBus().register(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) headLayout.getLayoutParams();
        lp.height = ScreenUtils.getScreenWidth(this);
        lp.weight = ScreenUtils.getScreenWidth(this);
        headLayout.setLayoutParams(lp);

        mPresenter.getDetail(giftId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(giftId);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getDetail(giftId);
            }
        });
    }


    @OnClick({R2.id.back_btn, R2.id.share_btn, R2.id.organization_layout, R2.id.bottom_layout})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.share_btn) {
            String coverUrl;
            if (mBean.getPicList() != null && mBean.getPicList().size() > 0) {
                coverUrl = mBean.getPicList().get(0);
            } else {
                coverUrl = "";
            }
            MShareBoard shareBoard = new MShareBoard(ShopRushPurchaseDetailActivity.this, mBean.getId() + "", mBean.getName(), coverUrl, mBean.getNote(), 39, false);
            shareBoard.showPopupWindow();
        } else if (viewId == R.id.organization_layout) {
            if (mBean != null && mBean.getShopId() != 0) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                        .withInt("shopId", mBean.getShopId())
                        .navigation();
            }
        } else if (viewId == R.id.bottom_layout) {
            if (!mBean.isReceived() && (mBean.getReceiveStatus() == 1 || mBean.getReceiveStatus() == 2 || mBean.getReceiveStatus() == 3)) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            String phoneNum = CommonUtils.getInstance().getUserName();
                            String sign = Md5Builder.encode(giftId + "-" + phoneNum + "-" + CommonUtils.getInstance().getSite() + "-qyhl");
                            ShopRushPurchaseDetailActivity.this.showLoading();
                            mPresenter.doRushPurchase(giftId, phoneNum, sign);
                        } else {
                            showToast("尚未登录或登录已失效！");
                            RouterManager.routerLogin(ShopRushPurchaseDetailActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });

            } else if (mBean.isReceived() && !mBean.isPay()) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_GIFT_ORDER)
                        .withInt("id", mBean.getUserGiftId())
                        .navigation();
            }
        }
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(ShopRushDetailBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        refresh.finishRefresh();
        dismissLoading();

        mBean = bean;

        List<ShopBaseBannerBean> picList = new ArrayList<>();
        for (int i = 0; i < bean.getPicList().size(); i++) {
            picList.add(new ShopBaseBannerBean(bean.getPicList().get(i)));
        }

        xBanner.setBannerData(R.layout.shop_item_rush_purchase_detail, picList);
        xBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                ResizableImageView bannerCover = view.findViewById(R.id.cover);
                if (ShopRushPurchaseDetailActivity.this.getApplicationContext() != null) {
                    Glide.with(ShopRushPurchaseDetailActivity.this.getApplicationContext())
                            .load(((ShopBaseBannerBean) model).getImageUrl())
                            .placeholder(R.drawable.cover_normal_default)
                            .error(R.drawable.cover_normal_default)
                            .into(bannerCover);
                }
            }
        });

        if (bean.getTodayReceiveUser() != null) {
            message.setVisibility(View.VISIBLE);

            messageTxt.setText(bean.getTodayReceiveUser().getNickname() + "抢到了");
            if (ShopRushPurchaseDetailActivity.this.getApplicationContext() != null) {
                Glide.with(this.getApplicationContext())
                        .load(bean.getTodayReceiveUser().getLogo())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                        .into(messageHead);
            }

            countDownTimer = new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    message.setVisibility(View.GONE);
                }
            }.start();

        } else {
            message.setVisibility(View.GONE);
        }


        SpanUtils spanUtils = new SpanUtils(ShopRushPurchaseDetailActivity.this);
        if (bean.getPrice() == 0) {
            spanUtils.append("免费").setSpans(new TextAppearanceSpan(ShopRushPurchaseDetailActivity.this, R.style.shop_gift_price_one));
        } else {
            spanUtils.append("¥").setSpans(new TextAppearanceSpan(ShopRushPurchaseDetailActivity.this, R.style.shop_gift_price_three))
                    .append(bean.getPrice() + "").setSpans(new TextAppearanceSpan(ShopRushPurchaseDetailActivity.this, R.style.shop_gift_price_two));
        }
        price.setText(spanUtils.create());

        if (DateUtils.isBeforeTime(bean.getCountDownTime())) {
            timeTips.setText("距离结束");
            overTimer = new CountDownTimer(DateUtils.restDate(bean.getCountDownTime()), 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    timeDay.setText(DateUtils.restDate(mBean.getCountDownTime(), 1));
                    timeHour.setText(DateUtils.restDate(mBean.getCountDownTime(), 2));
                    timeMinute.setText(DateUtils.restDate(mBean.getCountDownTime(), 3));
                }

                @Override
                public void onFinish() {
                    mPresenter.getDetail(giftId);
                }
            }.start();
        } else {
            timeTips.setText("已结束");
            timeDay.setText("00");
            timeHour.setText("00");
            timeMinute.setText("00");
        }

        title.setText(bean.getName());

        expiryDate.setText(bean.getExchangeBeginDate() + " ~ " + bean.getExchangeEndDate());

        address.setText(bean.getAddress());

        organization.setText(bean.getOrganizer());
        if (bean.getShopId() == 0) {
            orgTag.setVisibility(View.GONE);
        } else {
            orgTag.setVisibility(View.VISIBLE);
        }

        introduction.setText(bean.getNote());

        restNum.setText("剩余" + bean.getRestCount() + "份");
        restNum.setVisibility(View.VISIBLE);
        bottomLayout.setGravity(Gravity.START);
        if (bean.isReceived()) {
            if (bean.isPay()) {
                rushPurchaseTxt.setText("已抢购");
                restNum.setTextColor(getResources().getColor(R.color.shop_common_message_deep));
                rushPurchaseTxt.setTextColor(getResources().getColor(R.color.shop_common_title));
                bottomLayout.setBackgroundResource(R.color.shop_background);
            } else {
                rushPurchaseTxt.setText("待支付");
                restNum.setTextColor(getResources().getColor(R.color.white));
                rushPurchaseTxt.setTextColor(getResources().getColor(R.color.white));
                bottomLayout.setBackgroundResource(R.color.shop_common_red);
            }
            if (bean.getReceiveStatus() == 5) {
                restNum.setVisibility(View.GONE);
                bottomLayout.setGravity(Gravity.CENTER_HORIZONTAL);
            }
        } else {
            switch (bean.getReceiveStatus()) {
                case 1:
                    rushPurchaseTxt.setText("立即抢");
                    restNum.setTextColor(getResources().getColor(R.color.white));
                    rushPurchaseTxt.setTextColor(getResources().getColor(R.color.white));
                    bottomLayout.setBackgroundResource(R.color.shop_common_red);
                    break;
                case 2:
                    rushPurchaseTxt.setText("立即抢");
                    restNum.setTextColor(getResources().getColor(R.color.white));
                    rushPurchaseTxt.setTextColor(getResources().getColor(R.color.white));
                    bottomLayout.setBackgroundResource(R.color.shop_common_red);
                    break;
                case 3:
                    rushPurchaseTxt.setText("即将售罄");
                    restNum.setTextColor(getResources().getColor(R.color.white));
                    rushPurchaseTxt.setTextColor(getResources().getColor(R.color.white));
                    bottomLayout.setBackgroundResource(R.color.shop_common_red);
                    break;
                case 4:
                    rushPurchaseTxt.setText("已售罄");
                    restNum.setTextColor(getResources().getColor(R.color.shop_common_message_deep));
                    rushPurchaseTxt.setTextColor(getResources().getColor(R.color.shop_common_title));
                    bottomLayout.setBackgroundResource(R.color.shop_background);
                    break;
                case 5:
                    rushPurchaseTxt.setText("已结束");
                    restNum.setTextColor(getResources().getColor(R.color.shop_common_message_deep));
                    rushPurchaseTxt.setTextColor(getResources().getColor(R.color.shop_common_title));
                    bottomLayout.setBackgroundResource(R.color.shop_background);
                    restNum.setVisibility(View.GONE);
                    bottomLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                    break;
            }
        }

        RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) imageLayout.getLayoutParams();
        imageLayout.setVisibility(View.VISIBLE);
        if (bean.getReceiveUserList() != null && bean.getReceiveUserList().size() > 0) {
            if (bean.getReceiveUserList().size() == 1) {
                picOne.setVisibility(View.VISIBLE);
                picTwo.setVisibility(View.GONE);
                picThree.setVisibility(View.GONE);
                linearParams.width = StringUtils.dip2px(this, 40);

                loadImage(bean.getReceiveUserList().get(0).getLogo(), picOne);
            } else if (bean.getReceiveUserList().size() == 2) {
                picOne.setVisibility(View.VISIBLE);
                picTwo.setVisibility(View.VISIBLE);
                picThree.setVisibility(View.GONE);

                linearParams.width = StringUtils.dip2px(this, 60);

                loadImage(bean.getReceiveUserList().get(0).getLogo(), picTwo);
                loadImage(bean.getReceiveUserList().get(1).getLogo(), picOne);
            } else {
                picOne.setVisibility(View.VISIBLE);
                picTwo.setVisibility(View.VISIBLE);
                picThree.setVisibility(View.VISIBLE);

                linearParams.width = StringUtils.dip2px(this, 80);

                loadImage(bean.getReceiveUserList().get(0).getLogo(), picThree);
                loadImage(bean.getReceiveUserList().get(1).getLogo(), picTwo);
                loadImage(bean.getReceiveUserList().get(2).getLogo(), picOne);
            }
            imageLayout.setLayoutParams(linearParams);
        } else {
            picOne.setVisibility(View.GONE);
            picTwo.setVisibility(View.GONE);
            picThree.setVisibility(View.GONE);

            imageLayout.setVisibility(View.GONE);
        }

    }

    private void loadImage(String url, RoundedImageView imageView) {
        if (ShopRushPurchaseDetailActivity.this.getApplicationContext() != null) {
            Glide.with(this.getApplicationContext())
                    .load(url)
                    .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).error(R.drawable.comment_head_default))
                    .into(imageView);
        }
    }

    @Override
    public void rushPurchaseResult(ShopRushPurchaseTicketBean bean) {
        ticketBean = bean;
        dismissLoading();
        if (mBean.getPrice() == 0) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_RESULT)
                    .withInt("type", 1)
                    .withInt("id", bean.getUserGiftId())
                    .navigation(this, REQUEST_CODE);
        } else {
            ARouter.getInstance()
                    .build(ARouterPathConstant.SHOP_GIFT_ORDER)
                    .withInt("id", bean.getUserGiftId())
                    .navigation();
        }
    }

    @Override
    public void setError(String msg) {
        dismissLoading();
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @Override
    public void rushPurchaseError(int code, String msg) {
        dismissLoading();
        switch (code) {
            case 1214:
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_RESULT)
                        .withInt("type", 3)
                        .navigation(this, REQUEST_CODE);
                break;
            case 1210:
            case 1211:
            case 1212:
            case 1213:
            case 1204:
                showToast(msg);
                break;
            default:
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_RUSH_PURCHASE_RESULT)
                        .withInt("type", 2)
                        .navigation(this, REQUEST_CODE);
                break;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }

        if (overTimer != null) {
            overTimer.cancel();
            overTimer = null;
        }
        BusFactory.getBus().unregister(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            switch (resultCode) {
                case RESULT_OK:
                    dismissLoading();
                    mPresenter.getDetail(giftId);
                    BusFactory.getBus().post(new Event.GiftRefresh(giftId, -1, ticketBean.getGiftRestCount()));
                    break;
                case 10:
                    mPresenter.getDetail(giftId);
                    BusFactory.getBus().post(new Event.GiftRefresh(giftId, 4));
                    break;
                case 20:
                    if (!mBean.isReceived() && (mBean.getReceiveStatus() == 1 || mBean.getReceiveStatus() == 2 || mBean.getReceiveStatus() == 3)) {
                        String phoneNum = CommonUtils.getInstance().getUserName();
                        String sign = Md5Builder.encode(giftId + "-" + phoneNum + "-" + CommonUtils.getInstance().getSite() + "-qyhl");
                        ShopRushPurchaseDetailActivity.this.showLoading();
                        mPresenter.doRushPurchase(giftId, phoneNum, sign);
                    }
                    break;
            }
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void doRefresh(Event.OrderRefresh event) {
        if (event != null) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPresenter.getDetail(giftId);
                }
            }, 3000);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            mPresenter.getDetail(giftId);
        }
    }


}
